<template>
  <el-dialog
      title="绑定 Google 身份验证器"
      v-model="visible"
      width="35%"
      :close-on-click-modal="false"
      @closed="closeDialog"
  >
    <div class="ga-dialog-content">
      <!-- 二维码 -->
      <div class="qrcode-container">
        <img :src="qrCodeUrl" alt="Google Authenticator QR Code" class="qrcode-image"/>
      </div>

      <!-- GA 密钥 -->
      <div class="ga-secret-key">
        <label>密钥：</label>
        <span class="key-text">{{ gaSecretKey }}</span>
        <el-button size="small" @click="copyGaSecretKey">复制</el-button>
      </div>

      <!-- 表单 -->
      <el-form ref="form" :model="formData" :rules="rules" label-width="100px" style="margin-top: 20px;">
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="formData.captcha" placeholder="请输入 Google 验证码"/>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
// 引入获取 GA 二维码接口
import {
  userGetGaQrcodeApi,
  userEditGaBindFlagApi
} from '@/api/mgt/power/user';

export default {
  data() {
    let checkCaptcha = (rule, value, callback) => {
      const reg = /^\d{6}$/;
      if (!value) {
        return callback(new Error("验证码不能为空"));
      } else {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("验证码必须为6位数字"));
        }
      }
    };
    return {
      visible: false,
      resolveCallback: null,
      qrCodeUrl: '',
      gaSecretKey: '',
      formData: {
        captcha: ''
      },
      rules: {
        captcha: [{required: true, validator: checkCaptcha, trigger: "change"}],
      }
    };
  },
  methods: {
    /**
     * 显示弹窗，可传入二维码地址和回调函数
     */
    async show(callback) {
      const res = await userGetGaQrcodeApi({});
      this.qrCodeUrl = res?.bizData?.content;
      this.gaSecretKey = res?.bizData?.key;

      this.resolveCallback = callback;
      this.visible = true;
    },

    /**
     * 提交表单并调用接口提交验证码
     */
    async submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const captcha = this.formData.captcha;

          userEditGaBindFlagApi({captcha}).then(res => {
            this.visible = false;

            // 调用外部回调（如果存在）
            if (this.resolveCallback) {
              this.resolveCallback(captcha);
            }
          });
        } else {
          return false;
        }
      });
    },


    /**
     * 关闭弹窗并重置表单
     */
    closeDialog() {
      this.visible = false;
      this.$refs.form.resetFields();
    },

    /**
     * 复制 GA 密钥到剪贴板
     */
    async copyGaSecretKey() {
      if (!this.gaSecretKey) {
        this.$message.warning('密钥为空，无法复制');
        return;
      }

      await navigator.clipboard.writeText(this.gaSecretKey);
      this.$message.success('复制成功');
    }
  }
};
</script>

<style scoped>
.ga-dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 20px;
}

.qrcode-container {
  margin-bottom: 20px;
  text-align: center;
}

.qrcode-image {
  width: 200px;
  height: 200px;
}

.ga-secret-key {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.key-text {
  font-family: monospace;
  font-weight: bold;
  color: #333;
}
</style>
